﻿using System;
using System.IO;
using AppCommon;
using Controller;
using Model;

public partial class ACPanel_NodeTour_AddEditTour : System.Web.UI.Page
{
    public static string _id;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindDatatoDDL.BindTourDiemDen(ddlTourdiemden);
            BindDatatoDDL.BindDiaDiem(ddlNoidi);
            BindDatatoDDL.BindDiaDiem(ddlNoiden);
            BindDatatoDDL.BindTourDocDao(ddlTourdocdao);
            BindDatatoDDL.BindTourLeTet(ddlTourletet);
            calendar1.SelectedDate = DateTime.Today;
            calendar2.SelectedDate = DateTime.Today;
            var id = Request.QueryString["Id"];
            tbId.Text = "VYCTour-" + Common.ConvertDateTimetoString();
            if (id != null)
            {
                id = id.Replace("'", "''");
                _id = id;
                BindData(id);
            }
        }
    }

    public void BindData(string id)
    {
        var tourController = new VYC01Controller();
        var tourInfo = tourController.GetById(id);
        if (tourInfo.Count <= 0)
        {
            litResult1.Text = "Lỗi! Không tồn tại thông tin về tour tương ứng." + id;
            litResult.Text = "<p class=\"alert alert-danger\">Lỗi! Không tồn tại thông tin về tour tương ứng.</p>";
        }
        else
        {
            ddlTourdiemden.SelectedValue = Convert.ToString(tourInfo[0].IdTourDiemDen);
            tbId.Text = tourInfo[0].Id;
            tbTieude.Text = tourInfo[0].TieuDe;
            tbTomtat.Text = tourInfo[0].TomTat;
            imgPopupAvatar.ImageUrl = Constants.UPLOAD_TOUR + tourInfo[0].AnhDaiDien;
            imgPopupAvatar.AlternateText = tourInfo[0].AnhDaiDien;
            imgPopupPanorama.ImageUrl = Constants.UPLOAD_TOUR + tourInfo[0].AnhPanorama;
            imgPopupPanorama.AlternateText = tourInfo[0].AnhPanorama;
            tbNoidung.Text = Server.HtmlDecode(tourInfo[0].NoiDung);
            tbSocho.Text = tourInfo[0].SoCho.ToString();
            // tbNgaydi.Text = tourInfo[0].NgayDi.ToString();
            calendar1.SelectedDate = Convert.ToDateTime(tourInfo[0].NgayDi.Date);
            calendar1.VisibleDate = Convert.ToDateTime(tourInfo[0].NgayDi.Date.ToString());
            // tbNgayden.Text = tourInfo[0].NgayDen.ToString();
            calendar2.SelectedDate = Convert.ToDateTime(tourInfo[0].NgayDen.Date);
            calendar2.VisibleDate = Convert.ToDateTime(tourInfo[0].NgayDen.Date.ToString());
            ddlNoidi.SelectedValue = tourInfo[0].IdNoiDi.ToString();
            ddlNoiden.SelectedValue = tourInfo[0].IdNoiDen.ToString();
            tbGiatour.Text = tourInfo[0].Gia.ToString();
            tbTags.Text = tourInfo[0].Tag;
            ddlTourdocdao.SelectedValue = Convert.ToString(tourInfo[0].IdTourDocDao);
            ddlTourletet.SelectedValue = Convert.ToString(tourInfo[0].IdTourLeTet);
            cbTrangThai.Checked = Convert.ToBoolean(tourInfo[0].TrangThai);
            cbHienthipanoramalon.Checked = Convert.ToBoolean(tourInfo[0].HienThiPanoramaLon);
        }
    }

    /// <summary>
    /// Xu ly them du lieu tour
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnThemvao_OnClick(object sender, EventArgs e)
    {
        try
        {            
            var info = new ModelVYC01();

            info.IdTourDiemDen = Convert.ToInt32(ddlTourdiemden.SelectedValue);
            // Get id sub loai tour
            var controller = new VYC0301Controller();
            var list = controller.GetById(Convert.ToInt32(ddlTourdiemden.SelectedValue));

            if (list.Count > 0)
            {
                info.IdSubLoaiTour = list[0].IdSubLoaiTour;
                var controller03 = new VYC03Controller();
                var list03 = controller03.GetById(list[0].IdSubLoaiTour);
                if (list03.Count > 0)
                {
                    info.IdLoaiTour = list03[0].IdLoaiTour;
                }
            }
            else
            {
                litResult.Text = "<p class=\"alert alert-danger\">Lỗi! Bạn chưa chọn tour điểm đến.</p>";
                return;
            }
            var tourController = new VYC01Controller();

            info.UniqueId = Common.ConvertToUnSign(tbTieude.Text.Trim());
            info.TieuDe = tbTieude.Text.Trim();
            // Anh dai dien
            if (imgUploadAnhdaidien.HasFile)
            {
                var pathAnhbia = Server.MapPath(Constants.UPLOAD_TOUR);
                if (!Directory.Exists(pathAnhbia))
                {
                    Directory.CreateDirectory(pathAnhbia);
                }
                // validate file image
                string[] validFileTypes = { "gif", "png", "jpg", "jpeg" };
                var extFile = Path.GetExtension(imgUploadAnhdaidien.PostedFile.FileName);
                var isValidate = false;

                if (extFile != null)
                {
                    foreach (var type in validFileTypes)
                    {
                        if (extFile.Equals("." + type))
                        {
                            isValidate = true;
                            break;
                        }
                    }
                }

                if (!isValidate)
                {
                    litResult1.Text = "Invalid file with extension!";
                    info.AnhDaiDien = Constants.NO_IMAGE;
                }
                else
                {

                    litResult1.Text = "Ok!";
                    // Luu file 
                    imgUploadAnhdaidien.SaveAs(pathAnhbia + tbId.Text + "_avatar_" + DateTime.Now.ToString("ddMMyyhhmmss") +
                                    extFile);
                    info.AnhDaiDien = tbId.Text + "_avatar_" + DateTime.Now.ToString("ddMMyyhhmmss") + extFile;
                }
            }
            else
            {
                info.AnhDaiDien = imgPopupAvatar.AlternateText;
            }
            // Anh panorama
            if (imgUploadAnhpanorama.HasFile)
            {
                var pathAnhbia = Server.MapPath(Constants.UPLOAD_TOUR);
                if (!Directory.Exists(pathAnhbia))
                {
                    Directory.CreateDirectory(pathAnhbia);
                }
                // validate file image
                string[] validFileTypes = { "gif", "png", "jpg", "jpeg" };
                var extFile = Path.GetExtension(imgUploadAnhpanorama.PostedFile.FileName);
                var isValidate = false;

                if (extFile != null)
                {
                    foreach (var type in validFileTypes)
                    {
                        if (extFile.Equals("." + type))
                        {
                            isValidate = true;
                            break;
                        }
                    }
                }

                if (!isValidate)
                {
                    litResult1.Text = "Invalid file with extension!";
                    info.AnhPanorama = Constants.NO_IMAGE;
                }
                else
                {

                    litResult1.Text = "Ok!";
                    // Luu file 
                    imgUploadAnhpanorama.SaveAs(pathAnhbia + tbId.Text + "_panorama_" + DateTime.Now.ToString("ddMMyyhhmmss") +
                                    extFile);
                    info.AnhPanorama = tbId.Text + "_panorama_" + DateTime.Now.ToString("ddMMyyhhmmss") + extFile;
                }
            }
            else
            {
                info.AnhPanorama = imgPopupPanorama.AlternateText;
            }
            //
            info.TomTat = tbTomtat.Text.Trim().Replace("'", "''");
            info.NoiDung = Server.HtmlEncode(tbNoidung.Text);
            info.SoCho = Convert.ToInt32(tbSocho.Text);
            // info.NgayDi = DateTime.Parse(tbNgaydi.Text);
            info.NgayDi = calendar1.SelectedDate;
            // info.NgayDen = DateTime.Parse(tbNgayden.Text);
            info.NgayDen = calendar2.SelectedDate;
            info.IdNoiDi = Convert.ToInt32(ddlNoidi.SelectedValue);
            info.IdNoiDen = Convert.ToInt32(ddlNoiden.SelectedValue);
            info.Gia = Convert.ToInt32(tbGiatour.Text);
            info.Tag = tbTags.Text;
            info.TrangThai = Convert.ToInt32(cbTrangThai.Checked);

            var userCookie = Request.Cookies["VYCTravel"];
            info.IdUser = Common.Decrypt(userCookie["Title"]); // Get in cookie

            info.HienThiPanoramaLon = Convert.ToInt32(cbHienthipanoramalon.Checked); // Set default is not show
            info.HienThiPanoramaNho = 0; // Set default is not show
            info.IdTourDocDao = ddlTourdocdao.SelectedValue;
            info.IdTourLeTet = ddlTourletet.SelectedValue;
            var isSuccess = 0;
            if (!string.IsNullOrEmpty(_id))
            {
                info.Id = _id;
                isSuccess = tourController.EditData(info);
            }
            else
            {
                info.Id = tbId.Text.Trim();
                isSuccess = tourController.AddData(info);
            }

            if (isSuccess == 0)
            {
                // Chua thanh cong
                litResult1.Text = "<span class=\"alert alert-danger\">Lỗi! Thêm dữ liệu thất bại.</span>";
                litResult.Text = "<p class=\"alert alert-danger\">Lỗi! Thêm dữ liệu thất bại.</p>";
            }
            else
            {
                litResult1.Text = "<span class=\"alert alert-success\">Thêm dữ liệu thành công.</span>";
                litResult.Text = "<p class=\"alert alert-success\">Thêm dữ liệu thành công.</p>";
                ResetInput();
            }

        }
        catch (Exception exc)
        {
            litResult1.Text = "<span class=\"alert alert-danger\">Lỗi! Thêm dữ liệu thất bại. " + exc.Message + "</span>";
            litResult.Text = "<p class=\"alert alert-danger\">Lỗi! Thêm dữ liệu thất bại.</p>";            
        }
    }

    /// <summary>
    /// Reset all input
    /// </summary>
    public void ResetInput()
    {
        tbTieude.Text = "";
        tbTomtat.Text = "";
        tbNoidung.Text = "";
        calendar1.SelectedDate = DateTime.Today;
        calendar2.SelectedDate = DateTime.Today;
        tbSocho.Text = "";
        tbTags.Text = "";
        tbGiatour.Text = "";
        cbTrangThai.Checked = false;
        _id = String.Empty;
    }    
}